import { useEffect } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { fetchUserList, setPage } from '../store/store';

export default function UserList() {
  const dispatch = useDispatch();
  const { list, page, size, loading, error } = useSelector((state) => state.users);

  useEffect(() => {
    dispatch(fetchUserList({ page, size }));
  }, [dispatch, page, size]);

  const handleNext = () => {
    dispatch(setPage(page + 1));
  };

  const handlePrev = () => {
    if (page > 1) dispatch(setPage(page - 1));
  };

  return (
    <div>
      <h2>用户列表（第 {page} 页）</h2>
      {loading && <p>加载中...</p>}
      {error && <p style={{ color: 'red' }}>{error}</p>}
      <ul>
        {list.map((user, index) => (
          <li key={user._id || index}>
            {user.name}（{user.price}）
          </li>
        ))}
      </ul>
      <div style={{ marginTop: 10 }}>
        <button onClick={handlePrev} disabled={page === 1}>上一页</button>
        <button onClick={handleNext}>下一页</button>
      </div>
    </div>
  );
}
